package management;

import dao.GoodsDao;
import pojo.entity.Goods;
import utils.AdminConnection;
import utils.DbUtil;
import utils.TimeoutScheduler;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;

import static dao.AdminDao.*;
import static dao.GoodsDao.*;
import static dao.UserDao.getUserByUsername;
import static management.CommonManagement.home;
import static management.CommonManagement.welcomePage;
import static utils.DbUtil.touchAdmin;
import static utils.DbUtil.touchUser;
import static vmmsClient.UserClient.sendLogToService;


/**
 * @Author: 周训发
 * @CreateTime: 2025-11-21
 * @Description: 管理员界面模块
 * @Version: 1.0
 */

public class AdminManagement {
    public static String ADMINNAME = null;  //当前登录的用户名
    public static boolean isFindAllGoods = false;  //是否查看全部商品
    public static boolean ADMIN_NEED_RELOGIN = false;

    /*======================================首页=========================================*/
    //登录成功
    public static void adminLoginTrue() throws SQLException {
        home();
        System.out.println("请选择操作功能：");
        System.out.println("1.查询商品列表 2.添加商品 3.修改商品 4.删除商品 5.消息通知  6.退出登录 7.退出");
        Scanner scanner = new Scanner(System.in);
        boolean flag = true;
        while (flag) {
            String ops = scanner.next();
            if (ADMIN_NEED_RELOGIN || isAdminOfflineInDB()) {
                System.out.println("【会话已过期，请重新登录】");
                ADMIN_NEED_RELOGIN = false;
                touchAdmin(getAdminByUsername(ADMINNAME).getId());
                welcomePage();          // 退回首页
                return;
            }
            switch (ops){
                case "1":{
                    isFindAllGoods = true;
                    findAllProduct();
                    flag = false;
                    break;
                }
                case "2":{
                    addGoods();
                    flag = false;
                    break;
                }
                case "3":{
                    isFindAllGoods = false;
                    findAllProduct();
                    modifyGoods();
                    flag = false;
                    break;
                }
                case "4":{
                    isFindAllGoods = false;
                    findAllProduct();
                    deleteGoods();
                    flag = false;
                    break;
                }
                case "5":{
                    messageManagement();
                    flag = false;
                    break;
                }
                case "6":{
                    setAdminOnlineStatus(ADMINNAME, 0);
                    sendLogToService("[下线日志] 管理员:" + ADMINNAME + " 已下线 " + java.time.LocalDateTime.now());
                    welcomePage();
                    flag = false;
                    break;
                }
                case "7":{
                    setAdminOnlineStatus(ADMINNAME, 0);
                    System.exit(0);
                    break;
                }
                default:{
                    System.out.println("操作错误！请重新输入");
                    break;
                }
            }
        }
    }
    private static void messageManagement() throws SQLException {
        PrintWriter out = AdminConnection.getWriter();
        BufferedReader in = AdminConnection.getReader();
        if (out == null || in == null) {
            System.out.println("尚未建立长连接，请先登录。");
            return;
        }
        Scanner sc = new Scanner(System.in);
//        out.println("IAMAdmin:" + ADMINNAME);
        touchUser(getAdminByUsername(ADMINNAME).getId());
        try {
            boolean flag = true;
            String[] users = null;
            while (flag) {
                out.println("GET_ONLINE_USERS");
                String resp = in.readLine();
                if (resp != null && resp.startsWith("ONLINEUsers:")) {
                    users = resp.split(":")[1].split(",");
                    if (users.length > 0 && !users[0].equals("暂无")) {
//                        System.out.println("当前在线用户：" + Arrays.toString(users));
                        flag = false;
                    } else {
                        System.out.println("暂无其他在线用户");
                        System.out.println("请选择一下操作");
                        System.out.println("1.再等一等（其他键，每30秒刷新一次） 2.返回主菜单 3.退出");
                        String input = sc.nextLine();
                        switch (input) {
                            case "2":
                                adminLoginTrue();
                                flag = false;
                                break;
                            case "3":
                                flag = false;
                                System.exit(0);
                                break;
                            default:
                                try {
                                    System.out.println("30 秒后自动重试...");
                                    Thread.sleep(30000);
                                } catch (InterruptedException ignored) {}
                                break;
                        }
                    }
                }
            }

            System.out.println("当前在线用户：" + Arrays.toString(users));
            System.out.println("请选择用户（序号）：");
            for (int i = 0; i < users.length; i++)
                System.out.printf("%d. %s%n", i + 1, users[i]);
            String targetUser = users[Integer.parseInt(sc.nextLine()) - 1];

            AdminConnection.send("ENTER:" + ADMINNAME + ":" + targetUser);
            System.out.println("SYS:已与用户 " + targetUser + " 建立会话，输入-1退出");

            while (true) {
                String msg = sc.nextLine();
                if ("-1".equals(msg)) break;
                AdminConnection.send("CHAT:" + ADMINNAME + ":" + targetUser + ":" + msg);
                touchAdmin(getAdminByUsername(ADMINNAME).getId());
                if (ADMIN_NEED_RELOGIN || isAdminOfflineInDB()) {
                    System.out.println("【会话已过期，请重新登录】");
                    ADMIN_NEED_RELOGIN = false;
                    touchAdmin(getAdminByUsername(ADMINNAME).getId());
                    welcomePage(); return;
                }
            }
            AdminConnection.send("EXIT:" + ADMINNAME + ":" + targetUser);
            System.out.println("已退出消息监听，回车返回主菜单...");
            sc.nextLine();
            adminLoginTrue();
        } catch (Exception e) {
            System.out.println("无法连接服务器。");
        }
    }

    /*======================================删除商品模块商品模块=========================================*/
   //批量删除商品
    private static void deleteGoods() {

        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入要删除的商品编号（批量以“,”分隔）：");
        String[] ids = scanner.next().split(",");
        int[] intIds = Arrays.stream(ids)
                .map(String::trim)
                .mapToInt(Integer::parseInt)
                .toArray();
        try {
            delBatchGoodsById(intIds);
            touchAdmin(getAdminByUsername(ADMINNAME).getId());
            System.out.println("删除成功！");
            // 放在 deleteGoods() 最后
            String log = "[管理员日志] 管理员:" + ADMINNAME + " 批量删除商品 id=" + Arrays.toString(intIds);
            sendLogToService(log);
            deleteGoodsOperation();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    //批量删除后操作选项
    public static void deleteGoodsOperation() throws SQLException {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请选择操作功能：");
        System.out.println("1.继续删除商品 2.查看商品列表 3.返回首页 4.退出");
        boolean flag = true;
        while (flag) {
            String ops = scanner.next();
            if (ADMIN_NEED_RELOGIN || isAdminOfflineInDB()) {
                System.out.println("【会话已过期，请重新登录】");
                ADMIN_NEED_RELOGIN = false;
                touchAdmin(getAdminByUsername(ADMINNAME).getId());
                welcomePage();          // 退回首页
                return;
            }
            switch (ops){
                case "1":{
                    isFindAllGoods = false;
                    findAllProduct();
                    deleteGoods();
                    flag = false;
                    break;
                }
                case "2":{
                    findAllProduct();
                    flag = false;
                    break;
                }
                case "3":{
                    adminLoginTrue();
                    flag = false;
                    break;
                }
                case "4":{
                    setAdminOnlineStatus(ADMINNAME, 0);
                    System.exit(0);
                    break;
                }
                default:{
                    System.out.println("操作错误！请重新输入");
                    break;
                }
            }
        }

    }

    /*======================================修改商品模块=========================================*/
    private static void modifyGoods() {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入所要修改的商品id：");
        int id = scanner.nextInt();
        try {
            Goods goods = getGoodsById(id);
            touchAdmin(getAdminByUsername(ADMINNAME).getId());
            if (goods == null){
                System.out.println("该商品不存在！");
            }else {
                System.out.println("请输入修改后的商品名称：");
                String newName = scanner.next();
                System.out.println("请输入修改后的商品价格：");
                double newPrice = scanner.nextDouble();
                System.out.println("请输入修改后的商品数量：");
                int newCount = scanner.nextInt();
                Goods g = new Goods(goods.getId(),newName,newPrice,newCount);
                updateGoods(g);
                touchAdmin(getAdminByUsername(ADMINNAME).getId());
                System.out.println(goods.getId()+"号商品已成功修改！");
                // 放在 modifyGoods() 最后
                String log = "[管理员日志] 管理员:" + ADMINNAME + " 修改商品 [" + newName + "] 新价格:" + newPrice + " 新数量:" + newCount;
                sendLogToService(log);
                updateGoodsOperation();
            }

        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
    //修改商品成功操作
    public static void updateGoodsOperation() throws SQLException {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请选择操作功能：");
        System.out.println("1.继续修改商品 2.查看商品列表 3.返回首页 4.退出");
        boolean flag = true;
        while (flag) {
            String ops = scanner.next();
            if (ADMIN_NEED_RELOGIN || isAdminOfflineInDB()) {
                System.out.println("【会话已过期，请重新登录】");
                ADMIN_NEED_RELOGIN = false;
                touchAdmin(getAdminByUsername(ADMINNAME).getId());
                welcomePage();          // 退回首页
                return;
            }
            switch (ops){
                case "1":{
                    isFindAllGoods = false;
                    findAllProduct();
                    modifyGoods();
                    flag = false;
                    break;
                }
                case "2":{
                    findAllProduct();
                    flag = false;
                    break;
                }
                case "3":{
                    adminLoginTrue();
                    flag = false;
                    break;
                }
                case "4":{
                    setAdminOnlineStatus(ADMINNAME, 0);
                    System.exit(0);
                    break;
                }
                default:{
                    System.out.println("操作错误！请重新输入");
                    break;
                }
            }
        }
    }

    /*======================================添加商品模块=========================================*/
    private static void addGoods() throws SQLException {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入商品名称：");
        String name = scanner.next();
        System.out.println("请输入商品价格：");
        double price = scanner.nextDouble();
        System.out.println("请输入商品数量：");
        int count = scanner.nextInt();
        Goods goods = new Goods();
        goods.setName(name);
        goods.setPrice(price);
        goods.setCount(count);
        if (count<=0){
            System.out.println("操作有误,商品数量不能小于0！");
            addGoodsOperation();
        }else {
            try {
                Goods g1 = getGoodsByName(goods.getName());
                touchAdmin(getAdminByUsername(ADMINNAME).getId());
                if (g1 != null){
                    System.out.println("该商品已存在！");
                    addGoodsOperation();
                }else {
                    GoodsDao.addGoods(goods);
                    //输出添加商品的信息
                    System.out.println("商品："+goods.getName()+"已成功添加");
                    String log = "[管理员日志] 管理员:" + ADMINNAME + " 新增商品 [" + name + "] 价格:" + price + " 数量:" + count;
                    sendLogToService(log);
                    addGoodsOperation();
                }
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }

    }
    //添加商品成功/失败后操作
    public static void addGoodsOperation() throws SQLException {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请选择操作功能：");
        System.out.println("1.继续添加商品 2.查看商品列表 3.返回首页 4.退出");
        boolean flag = true;
        while (flag) {
            String ops = scanner.next();
            if (ADMIN_NEED_RELOGIN || isAdminOfflineInDB()) {
                System.out.println("【会话已过期，请重新登录】");
                ADMIN_NEED_RELOGIN = false;
                touchAdmin(getAdminByUsername(ADMINNAME).getId());
                welcomePage();          // 退回首页
                return;
            }
            switch (ops){
                case "1":{

                    addGoods();
                    flag = false;
                    break;
                }
                case "2":{
                    findAllProduct();
                    flag = false;
                    break;
                }
                case "3":{
                    adminLoginTrue();
                    flag = false;
                    break;
                }
                case "4":{
                    setAdminOnlineStatus(ADMINNAME, 0);
                    System.exit(0);
                    break;
                }
                default:{
                    System.out.println("操作错误！请重新输入");
                    break;
                }
            }
        }
    }

    /*======================================查询商品模块=========================================*/
    //查询全部商品
    private static void findAllProduct() {
        try {
            List<Goods> goodsList = query();
            touchAdmin(getAdminByUsername(ADMINNAME).getId());
            if (goodsList.size() <= 0){
                System.out.println("暂无商品，快去添加商品吧！");
            }else {
                int count = 0;
                for (Goods goods : goodsList) {
                    //判断所有的商品数量是否为0，如果都为0，则提示商品已售完
                    if (goods.getCount() == 0){
                        count++;
                    }
                }
                if (count == goodsList.size()){
                    System.out.println("商品已售完！快去补货吧~");
                    emptyGoodsOperation();
                }
                System.out.printf("%-10s%-10s%-10s%-10s%n", "商品编号", "商品名称", "商品价格", "商品数量");
                //否则，还存在商品未售卖，则继续显示
                for (Goods goods : goodsList) {
                    System.out.printf("%-13d%-11s%-13.1f%-10d%n", goods.getId(), goods.getName(), goods.getPrice(), goods.getCount());
                }
                if (isFindAllGoods){
                    findAllGoodsOrMarginOPeration();
                }
            }

        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
    //暂无商品或商品已售完的操作
    public static void emptyGoodsOperation() throws SQLException {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请选择操作功能：");
        System.out.println("1.添加商品 2.去补货 3.删除商品 4.返回首页 5.退出");
        boolean flag = true;
        while (flag) {
            String ops = scanner.next();
            if (ADMIN_NEED_RELOGIN || isAdminOfflineInDB()) {
                System.out.println("【会话已过期，请重新登录】");
                ADMIN_NEED_RELOGIN = false;
                touchAdmin(getAdminByUsername(ADMINNAME).getId());
                welcomePage();          // 退回首页
                return;
            }
            switch (ops){
                case "1":{
                    addGoods();
                    flag = false;
                    break;
                }
                case "2":{
                    isFindAllGoods = false;
                    updateGoodsCountById();
                    flag = false;
                    break;
                }
                case "3":{
                    isFindAllGoods=false;
                    deleteGoods();
                    flag = false;
                    break;
                }
                case "4":{
                    adminLoginTrue();
                    flag = false;
                    break;
                }
                case "5":{
                    setAdminOnlineStatus(ADMINNAME, 0);
                    System.exit(0);
                    break;
                }
                default:{
                    System.out.println("操作错误！请重新输入");
                    break;
                }
            }
        }
    }

    //根据id修改商品的数量---补货
    private static void updateGoodsCountById() {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入所要修改的商品id：");
        int id = scanner.nextInt();
        try {
            Goods goods = getGoodsById(id);
            touchAdmin(getAdminByUsername(ADMINNAME).getId());
            if (goods == null){
                System.out.println("该商品不存在！");
            }else {
                System.out.println("请输入修改后的商品数量：");
                int newCount = scanner.nextInt();
                Goods g = new Goods(goods.getId(),goods.getName(),goods.getPrice(),newCount);
                updateGoods(g);
                touchAdmin(getAdminByUsername(ADMINNAME).getId());
                System.out.println(goods.getId()+"号商品已成功修改！");
                updateGoodsCountOperation();
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
    //补货后操作
    public static void updateGoodsCountOperation() throws SQLException {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请选择操作功能：");
        System.out.println("1.继续补货 2.查看商品列表 3.返回首页 4.退出");
        boolean flag = true;
        while (flag) {
            String ops = scanner.next();
            if (ADMIN_NEED_RELOGIN || isAdminOfflineInDB()) {
                System.out.println("【会话已过期，请重新登录】");
                ADMIN_NEED_RELOGIN = false;
                touchAdmin(getAdminByUsername(ADMINNAME).getId());
                welcomePage();          // 退回首页
                return;
            }
            switch (ops){
                case "1":{
                    isFindAllGoods = false;
                    findAllProduct();
                    updateGoodsCountById();
                    flag = false;
                    break;
                }
                case "2":{
                    findAllProduct();
                    flag = false;
                    break;
                }
                case "3":{
                    adminLoginTrue();
                    flag = false;
                    break;
                }
                case "4":{
                    setAdminOnlineStatus(ADMINNAME, 0);
                    System.exit(0);
                    break;
                }
                default:{
                    System.out.println("操作错误！请重新输入");
                    break;
                }
            }
        }

    }

    //查看全部商品或查看余额后操作
    public static void findAllGoodsOrMarginOPeration() throws SQLException {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请选择操作功能：");
        System.out.println("1.去添加商品 2.去修改商品 3.去删除商品 4.返回首页 5.退出");
        boolean flag = true;
        while (flag) {
            String ops = scanner.next();
            if (ADMIN_NEED_RELOGIN || isAdminOfflineInDB()) {
                System.out.println("【会话已过期，请重新登录】");
                ADMIN_NEED_RELOGIN = false;
                touchAdmin(getAdminByUsername(ADMINNAME).getId());
                welcomePage();          // 退回首页
                return;
            }
            switch (ops){
                case "1":{
                    addGoods();
                    flag = false;
                    break;
                }
                case "2":{
                    isFindAllGoods = false;
                    findAllProduct();
                    modifyGoods();
                    flag = false;
                    break;
                }
                case "3":{
                    isFindAllGoods = false;
                    findAllProduct();
                    deleteGoods();
                    flag = false;
                    break;
                }
                case "4":{
                    adminLoginTrue();
                    flag = false;
                    break;
                }
                case "5":{
                    setAdminOnlineStatus(ADMINNAME, 0);
                    System.exit(0);
                    break;
                }
                default:{
                    System.out.println("操作错误！请重新输入");
                    break;
                }
            }
        }
    }

}
